package www.wen.com.common.lib.extension

import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2

/**
 * @author WEN
 * @Description: Banner 的扩展类
 * @date 2021/7/1 19:26
 */


inline fun ViewPager2.onPageScrolled(
        crossinline action: (
                position: Int, positionOffset: Float, positionOffsetPixels: Int
        ) -> Unit
) = addOnPageChangeListener(onPageScrolled = action)


inline fun ViewPager2.onPageSelected(
        crossinline action: (
                position: Int
        ) -> Unit
) = addOnPageChangeListener(onPageSelected = action)


inline fun ViewPager2.onPageScrollStateChanged(
        crossinline action: (state: Int) -> Unit
) = addOnPageChangeListener(onPageScrollStateChanged = action)


inline fun ViewPager2.addOnPageChangeListener(
        crossinline onPageScrolled: (
                position: Int, positionOffset: Float, positionOffsetPixels: Int
        ) -> Unit = { _, _, _ -> },
        crossinline onPageSelected: (
                position: Int
        ) -> Unit = { _ -> },
        crossinline onPageScrollStateChanged: (state: Int) -> Unit = {}
): ViewPager2.OnPageChangeCallback {

    val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {

        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            onPageScrolled.invoke(position, positionOffset, positionOffsetPixels)
        }

        override fun onPageSelected(position: Int) {
            onPageSelected.invoke(position)
        }

        override fun onPageScrollStateChanged(state: Int) {
            onPageScrollStateChanged.invoke(state)
        }
    }
    registerOnPageChangeCallback(onPageChangeCallback)
    return onPageChangeCallback
}

fun <BA: FragmentStateAdapter> ViewPager2.configuration(
        pageLimit: Int,
        position: Int = 0,
        smoothScroll: Boolean = true,
        enabledSlide: Boolean = true,
        provideAdapter:()->BA,
        onPageSelectedBA:((position: Int) -> Unit)? = null
) {
    isUserInputEnabled = enabledSlide
    offscreenPageLimit = pageLimit
    adapter = provideAdapter.invoke()
//    setCurrentItem(position, smoothScroll)
    onPageSelectedBA?.run { onPageSelected(this) }
}

